package lzupdater.utils;

import java.util.ArrayList;
import java.util.LinkedList;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * 
 * @author Fraskor
 */
public class StatusItemManager extends LinkedList<StatusItem> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1906624660625862136L;
	private final static String importingData = "Importing data for";
	private final static String succesfulImport = "Character successfully updated";

	private boolean anyCriticalItem;

	public StatusItemManager(Text text) {
		StringBuffer buffer = new StringBuffer();
		for (String line : text) {
			buffer.append(line);
		}

		int cursor = 0;
		int idxStatus;
		int idxGuil;
		int idxGreater;
		int idxLower;

		anyCriticalItem = false;

		clear();
		while (true) {
			if ((idxStatus = buffer.indexOf("statusItem", cursor)) < 0)
				break;
			if ((idxGuil = buffer.indexOf("'", idxStatus)) < 0)
				break;
			if ((idxGreater = buffer.indexOf(">", idxGuil)) < 0)
				break;
			if ((idxLower = buffer.indexOf("<", idxGreater)) < 0)
				break;

			StatusItem item = new StatusItem(buffer.substring(idxStatus,
					idxGuil), buffer.substring(idxGreater + 1, idxLower));
			anyCriticalItem = anyCriticalItem || item.isCritical();
			add(item);
			cursor = idxLower;
		}
		;
	}

	public boolean isAnyCriticalItem() {
		return anyCriticalItem;
	}

	public ArrayList<String> extractUpdatedCharacters() {
		ArrayList<String> resultat = new ArrayList<String>();

		String name = null;
		for (StatusItem si : this) {
			if (si.getMsg().contains(importingData)) {
				name = si.getMsg().substring(importingData.length(),
						si.getMsg().indexOf(".", importingData.length()))
						.trim();
			}
			if (si.getMsg().contains(succesfulImport) && name != null) {
				resultat.add(name);
			}
		}
		return resultat;
	}

}
